package com.wgke.bluetooth.vm;

import android.util.Log;

import androidx.lifecycle.MutableLiveData;

import com.google.gson.reflect.TypeToken;
import com.wgke.bluetooth.db.AppDatabase;
import com.wgke.bluetooth.db.CmdEntity;
import com.wgke.bluetooth.db.TypeEntity;
import com.wgke.bluetooth.tools.BtMsg;
import com.wgke.bluetooth.utils.Async;
import com.wgke.bluetooth.utils.CommonUtil;
import com.wgke.bluetooth.utils.FileUtil;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

public class SettingsVM extends BaseVM {
    public MutableLiveData<List<CmdEntity>> list = new MutableLiveData<>(new ArrayList<>());

    public void loadCmdList() {
        Async.getInstance().await(() -> {
            List<TypeEntity> mList = AppDatabase.getDatabase(CommonUtil.getContext()).typeDao().getAllTypeEntities();
            if (mList.isEmpty()) {
                TypeEntity entity = new TypeEntity();
                entity.name = "默认";
                entity.projectName = "默认";
                AppDatabase.getDatabase(CommonUtil.getContext()).typeDao().insert(entity);
            }
            list.postValue(Async.getInstance().getDao().getAll());
        });
    }

    public boolean saveJsonToDb(List<CmdEntity> data) {
        long time = System.currentTimeMillis();
        if (data == null || data.isEmpty()) {
            Log.e("SettingsVM", "data is null ");
            return false;
        }
        for (CmdEntity entity : data) {
            entity.time = time;
            entity.describe = "";
            String cmd = entity.cmd;

            byte[] bytes = BtMsg.hexStringToByteArray(cmd);
            if (bytes != null) {
                StringBuilder hexString1 = new StringBuilder();
                for (byte b : bytes) {
                    hexString1.append(String.format("%02X ", b));
                }
                entity.cmd = hexString1.toString().trim();
                Async.getInstance().getDao().insertAll(entity);
            }

        }
        Log.e("SettingsVM", "createCmd: " + data.size());
        loadCmdList();
        return true;
    }

    public void createCmd() {
        Async.getInstance().await(() -> {
            String json = FileUtil.loadJsFromAssets("l5r5_2.json");
            Type userListType = new TypeToken<List<CmdEntity>>() {
            }.getType();
            List<CmdEntity> data = gson.fromJson(json, userListType);
            saveJsonToDb(data);
        });
    }
}
